#include "ConnectWidget.h"

ConnectWidget::ConnectWidget(QWidget *parent, Network::ConnectionStatus * status) :
    QWidget(parent) {
    connectionStatus = status;
    clientSocket = new QTcpSocket(this);

    createWidgets();
    createLayouts();
    connectSignalSlots();
}

ConnectWidget::~ConnectWidget() {
    if (clientSocket != NULL) {
        if (clientSocket->state() != QAbstractSocket::UnconnectedState) {
            clientSocket->disconnectFromHost();
            clientSocket->waitForDisconnected();
        }
    }
}

void ConnectWidget::createWidgets() {
    hostAddressLabel = new QLabel(tr("Host Address:"));
    hostAddressLabel->setAlignment(Qt::AlignLeft);
    hostAddressEdit = new QLineEdit();
    hostAddressEdit->setAlignment(Qt::AlignLeft);
    connectButton = new QPushButton(tr("Connect"));
}

void ConnectWidget::createLayouts() {
    QVBoxLayout * mainLayout = new QVBoxLayout;
    mainLayout->addWidget(hostAddressLabel);
    mainLayout->addWidget(hostAddressEdit);
    mainLayout->addWidget(connectButton);
    mainLayout->setMargin(MARGINS);
    mainLayout->setAlignment(Qt::AlignCenter);
    setLayout(mainLayout);
}

void ConnectWidget::connectSignalSlots() {
    connect(hostAddressEdit, SIGNAL(returnPressed()), connectButton, SLOT(click()));
    connect(connectButton, SIGNAL(clicked()), this, SLOT(connectOnClick()));
    connect(clientSocket, SIGNAL(connected()), this, SLOT(clientNewConnection()));
    connect(clientSocket, SIGNAL(disconnected()), this, SLOT(socketDisconnect()));
    connect(clientSocket, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(connectionError(QAbstractSocket::SocketError)));
}

void ConnectWidget::connectOnClick() {
    clientSocket->connectToHost(QHostAddress(hostAddressEdit->text()), PORT);
    changeConnectionStatus(Network::CLIENT_WAITING);
}

void ConnectWidget::clientNewConnection() {
    changeConnectionStatus(Network::CLIENT_CONNECTED);
}

void ConnectWidget::connectionError(QAbstractSocket::SocketError socketError) {
    emit connectionStatusChanged(Network::DISCONNECTED);
}

void ConnectWidget::socketDisconnect() {
    //changeConnectionStatus(Network::DISCONNECTED);
}

void ConnectWidget::changeConnectionStatus(Network::ConnectionStatus status) {
    switch (status) {
    case Network::DISCONNECTED:
        connectButton->setEnabled(true);
        if (clientSocket->state() != QAbstractSocket::UnconnectedState) {
            clientSocket->disconnectFromHost();
        }
        break;
    case Network::HOSTING_WAITING:
        connectButton->setEnabled(false);
        break;
    case Network::HOSTING_CONNECTED:
        connectButton->setEnabled(false);
        break;
    case Network::CLIENT_WAITING:
        connectButton->setEnabled(false);
        break;
    case Network::CLIENT_CONNECTED:
        connectButton->setEnabled(false);
        break;
    }
    if (*connectionStatus != status) {
        *connectionStatus = status;
        emit connectionStatusChanged(status);
    }
}
